<template>
  <div class="project-detail">
    <div class="breadcrumb">
      <router-link to="/dashboard" class="breadcrumb-link">
        <i class="fas fa-home"></i> 控制面板
      </router-link>
      <span class="breadcrumb-divider">&gt;</span>
      <span class="breadcrumb-current">项目详情</span>
    </div>
    
    <div v-if="loading" class="loading">
      <div class="loading-spinner"></div>
      <p>数据加载中，请稍候...</p>
    </div>
    
    <div v-else-if="error" class="error">
      <div class="error-icon">
        <i class="fas fa-exclamation-circle">项目名称</i>
      </div>
      <p>{{ error }}</p>
      <button @click="reloadProject" class="btn btn-outline-primary">
        <i class="fas fa-sync"></i> 重新加载
      </button>
    </div>
    
    <div v-else class="project-content">
      <div class="project-header">
        <div class="title-container">
          <h1>{{ project.description }}</h1>
          <div class="project-meta">
            <div class="project-status" :class="getStatusClass(project.status)">
              {{ getStatusText(project.status) }}
            </div>
            <div class="project-id">项目ID: <span class="id-value">{{ project.id }}</span></div>
          </div>
        </div>
        <div class="header-actions">
          <router-link to="/dashboard" class="btn btn-outline">
            <i class="fas fa-arrow-left"></i> 返回列表
          </router-link>
        </div>
      </div>
      
      <div class="project-info-grid">
        <div class="info-card description-card">
          <div class="card-header">
            <h2><i class="fas fa-user-md"></i>项目描述</h2>
          </div>
          <div class="card-body">
            <p>{{ project.researcherInfo }}</p>
          </div>
        </div>
        
        <!-- <div class="info-card researcher-card">
          <div class="card-header">
            <h2><i class="fas fa-user-md"></i> 研究者信息</h2>
          </div>
          <div class="card-body">
            <div class="researcher-info">
              <div class="info-item">
                <i class="fas fa-user"></i>
                <span>{{ formatResearcherInfo(project.researcherInfo) }}</span>
              </div>
              <div v-if="project.affiliationInfo" class="info-item">
                <i class="fas fa-university"></i>
                <span>{{ project.affiliationInfo }}</span>
              </div>
              <div v-if="project.contactInfo" class="info-item">
                <i class="fas fa-envelope"></i>
                <span>{{ project.contactInfo }}</span>
              </div>
            </div>
          </div>
        </div> -->
        
        <div class="info-card timeline-card">
          <div class="card-header">
            <h2><i class="fas fa-clock"></i> 项目时间线</h2>
          </div>
          <div class="card-body">
            <div class="timeline">
              <div class="timeline-item">
                <div class="timeline-icon creation-icon">
                  <i class="fas fa-plus-circle"></i>
                </div>
                <div class="timeline-content">
                  <h4>创建时间</h4>
                  <time>{{ formatDate(project.creationTime) }}</time>
                </div>
              </div>
              
              <div class="timeline-item">
                <div class="timeline-icon update-icon">
                  <i class="fas fa-edit"></i>
                </div>
                <div class="timeline-content">
                  <h4>最后更新</h4>
                  <time>{{ formatDate(project.lastUpdateTime) }}</time>
                </div>
              </div>
              
              <div v-if="project.completed" class="timeline-item">
                <div class="timeline-icon complete-icon">
                  <i class="fas fa-check-circle"></i>
                </div>
                <div class="timeline-content">
                  <h4>完成时间</h4>
                  <time>{{ formatDate(project.lastUpdateTime) }}</time>
                </div>
              </div>
              
              <div v-if="project.isDeleted" class="timeline-item">
                <div class="timeline-icon delete-icon">
                  <i class="fas fa-trash-alt"></i>
                </div>
                <div class="timeline-content">
                  <h4>删除时间</h4>
                  <time>{{ formatDate(project.deletionTime) }}</time>
                  <div v-if="project.deletionReason" class="timeline-reason">
                    <i class="fas fa-info-circle"></i> 删除原因: {{ project.deletionReason }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="info-card history-card" v-if="project.history && project.history.length > 0">
          <div class="card-header">
            <h2><i class="fas fa-history"></i> 项目历史记录</h2>
          </div>
          <div class="card-body">
            <div class="history-list">
              <div v-for="(history, index) in project.history" :key="index" class="history-item">
                <div class="history-meta">
                  <span class="history-date" v-if="history.details && history.details[2]">
                    <i class="fas fa-calendar-alt"></i> {{ formatDate(history.details[2]) }}
                  </span>
                </div>
                <div class="history-details" v-if="history.details">
                  <div class="history-operation">
                    <span class="operation-badge" :class="'operation-' + getOperationType(history.details[1]).toLowerCase()">
                      {{ getOperationType(history.details[1]) }}
                    </span>
                  </div>
                  <div v-if="history.details[3]" class="history-reason">
                    <i class="fas fa-comment"></i> {{ history.details[3] }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="info-card transaction-card" v-if="project.transactions && project.transactions.length > 0">
          <div class="card-header">
            <h2><i class="fas fa-exchange-alt"></i> 交易记录</h2>
          </div>
          <div class="card-body">
            <div class="transactions-list">
              <div v-for="(tx, index) in project.transactions" :key="index" class="transaction-item">
                <div class="tx-hash">
                  <i class="fas fa-hashtag"></i>
                  <code>{{ formatHash(tx) }}</code>
                </div>
                <button @click="fetchTransactionDetails(tx)" class="btn btn-sm btn-primary">
                  <i class="fas fa-search"></i> 查看详情
                </button>
              </div>
            </div>
          </div>
        </div>
        
        <div v-if="transactionDetails" class="info-card details-card">
          <div class="card-header">
            <h2><i class="fas fa-info-circle"></i> 交易详情</h2>
          </div>
          <div class="card-body">
            <div class="details-list">
              <div class="detail-item" v-for="(value, key) in formatTransactionDetails(transactionDetails)" :key="key">
                <div class="detail-label">{{ formatKey(key) }}</div>
                <div class="detail-value">{{ value }}</div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="info-card actions-card">
          <div class="card-header">
            <h2><i class="fas fa-tools"></i> 项目操作</h2>
          </div>
          <div class="card-body">
            <div class="actions-section">
              <div class="action-group">
                <h3><i class="fas fa-cog"></i> 项目管理</h3>
                <div class="action-buttons">
                  <button v-if="true || (canEditProject && project.status === 'ACTIVE')" 
                         class="btn btn-primary action-btn"
                         @click="editProject">
                    <i class="fas fa-edit"></i> 修改项目
                  </button>
                  
                  <button v-if="true || (isProjectCreator && project.status === 'ACTIVE')" 
                         class="btn btn-success action-btn"
                         @click="completeProject">
                    <i class="fas fa-check-circle"></i> 完成项目
                  </button>
                  
                  <button v-if="true || canDeleteProject" 
                         class="btn btn-danger action-btn"
                         @click="showDeleteConfirmation = true">
                    <i class="fas fa-trash"></i> 删除项目
                  </button>
                </div>
              </div>
              
              <div class="action-group">
                <h3><i class="fas fa-database"></i> 数据操作</h3>
                <div class="action-buttons">
                  <button v-if="isAuthenticated && project.status === 'ACTIVE' && !isProjectCreator" 
                         class="btn btn-primary action-btn"
                         @click="showContributionForm = true">
                    <i class="fas fa-upload"></i> 贡献数据
                  </button>
                  
                  <button class="btn btn-secondary action-btn" @click="verifyProjectHash">
                    <i class="fas fa-shield-alt"></i> 验证项目哈希
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 添加项目哈希数据显示 -->
        <div class="info-card hash-card" v-if="project.dataHash">
          <div class="card-header">
            <h2><i class="fas fa-fingerprint"></i> 项目数据哈希</h2>
          </div>
          <div class="card-body">
            <div class="hash-value">
              <code>{{ formatHash(project.dataHash) }}</code>
              <button @click="copyToClipboard(project.dataHash)" class="btn btn-sm btn-outline">
                <i class="fas fa-copy"></i> 复制完整哈希
              </button>
            </div>
            <div class="hash-info">
              <small class="text-muted">数据哈希用于验证项目数据的完整性，可用于区块链验证</small>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 删除确认对话框 -->
      <div v-if="showDeleteConfirmation" class="modal">
        <div class="modal-content modal-confirmation">
          <div class="modal-header delete-header">
            <h3><i class="fas fa-exclamation-triangle"></i> 确认删除项目</h3>
            <button class="close-btn" @click="showDeleteConfirmation = false">&times;</button>
          </div>
          <div class="modal-body">
            <div class="delete-project-info">
              <div class="project-title-preview">
                <span class="label">项目名称:</span>
                <span class="value">{{ project.title }}</span>
              </div>
              <div class="project-id-preview">
                <span class="label">项目ID:</span>
                <span class="value">{{ project.id }}</span>
              </div>
            </div>
            
            <div class="warning-box">
              <div class="warning-icon">
                <i class="fas fa-exclamation-circle"></i>
              </div>
              <div class="warning-message">
                <p>您即将永久删除此项目，此操作<span class="text-danger">不可撤销</span>。</p>
                <p>删除后，项目将被标记为已删除状态，且不会出现在常规项目列表中。</p>
              </div>
            </div>
            
            <div class="form-group delete-reason-group">
              <label for="deleteReason">
                <i class="fas fa-comment-alt"></i> 删除原因<span class="required">*</span>
              </label>
              <textarea 
                id="deleteReason" 
                v-model="deleteReason" 
                rows="3" 
                class="form-control"
                placeholder="请输入删除此项目的原因，例如'项目已完成'或'项目信息错误'" 
                required
              ></textarea>
              <small class="form-text text-muted">
                <i class="fas fa-info-circle"></i> 删除原因将被记录在区块链上，作为项目历史的一部分
              </small>
            </div>
          </div>
          <div class="modal-actions">
            <button class="btn btn-secondary" @click="showDeleteConfirmation = false">
              <i class="fas fa-arrow-left"></i> 取消操作
            </button>
            <button 
              class="btn btn-danger delete-confirm-btn" 
              @click="deleteProject" 
              :disabled="!deleteReason.trim()"
              :class="{'btn-disabled': !deleteReason.trim()}"
            >
              <i class="fas fa-trash"></i> 确认删除
            </button>
          </div>
        </div>
      </div>
      
      <!-- 贡献表单 -->
      <div v-if="showContributionForm" class="modal">
        <div class="modal-content">
          <div class="modal-header">
            <h3><i class="fas fa-upload"></i> 贡献医疗数据</h3>
            <button class="close-btn" @click="showContributionForm = false">&times;</button>
          </div>
          <div class="modal-body">
            <div class="form-group">
              <label for="dataType">数据类型:</label>
              <select id="dataType" v-model="contribution.dataType" class="form-control">
                <option value="MEDICAL_IMAGE">医学影像</option>
                <option value="PATIENT_RECORD">病历记录</option>
                <option value="LAB_RESULT">实验室结果</option>
                <option value="OTHER">其他</option>
              </select>
            </div>
            <div class="form-group">
              <label for="dataDescription">数据描述:</label>
              <textarea id="dataDescription" class="form-control" v-model="contribution.dataDescription" rows="3" placeholder="请描述您提供的数据"></textarea>
            </div>
            <div class="form-group">
              <label for="dataUrl">数据链接:</label>
              <input id="dataUrl" class="form-control" type="text" v-model="contribution.dataUrl" placeholder="请输入数据链接或摘要">
              <small class="form-text text-muted">请提供加密的数据链接或摘要</small>
            </div>
          </div>
          <div class="modal-actions">
            <button class="btn btn-secondary" @click="showContributionForm = false">
              <i class="fas fa-times"></i> 取消
            </button>
            <button class="btn btn-success" @click="submitContribution" :disabled="contributionLoading">
              <i class="fas fa-paper-plane"></i> {{ contributionLoading ? '提交中...' : '提交贡献' }}
            </button>
          </div>
        </div>
      </div>
      
      <!-- 验证项目哈希对话框 -->
      <div v-if="showHashVerification" class="modal">
        <div class="modal-content">
          <div class="modal-header">
            <h3><i class="fas fa-shield-alt"></i> 验证项目哈希</h3>
            <button class="close-btn" @click="showHashVerification = false">&times;</button>
          </div>
          <div class="modal-body">
            <div class="form-group">
              <label for="projectHash">输入项目哈希值:</label>
              <input id="projectHash" class="form-control hash-input" type="text" v-model="hashToVerify" placeholder="请输入项目哈希值">
            </div>
            <div v-if="verificationResult !== null" class="verification-result" 
                :class="{ 'verification-success': verificationResult, 'verification-failure': !verificationResult }">
              <i :class="verificationResult ? 'fas fa-check-circle' : 'fas fa-times-circle'"></i>
              {{ verificationResult ? '验证成功！哈希值匹配' : '验证失败！哈希值不匹配' }}
            </div>
          </div>
          <div class="modal-actions">
            <button class="btn btn-secondary" @click="showHashVerification = false">
              <i class="fas fa-times"></i> 取消
            </button>
            <button class="btn btn-primary" @click="doVerifyHash">
              <i class="fas fa-check"></i> 验证
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import axios from 'axios'

export default {
  name: 'ProjectDetail',
  props: {
    id: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      loading: true,
      error: null,
      showContributionForm: false,
      showDeleteConfirmation: false,
      showHashVerification: false,
      deleteReason: '',
      hashToVerify: '',
      verificationResult: null,
      transactionDetails: null,
      contribution: {
        dataType: 'MEDICAL_IMAGE',
        dataDescription: '',
        dataUrl: ''
      },
      contributionLoading: false
    }
  },
  computed: {
    ...mapGetters([
      'currentUser',
      'isAuthenticated'
    ]),
    
    project() {
      return this.$store.state.projects.currentProject
    },
    
    isProjectCreator() {
      console.log('检查创建者权限:', {
        isAuthenticated: this.isAuthenticated,
        hasProject: !!this.project,
        hasUser: !!this.currentUser,
        userId: this.currentUser?.id,
        projectResearcherId: this.project?.researcherId
      });
      
      // 在调试模式下直接返回true，允许任何人编辑
      // 在生产环境中应该移除这行
      return true;
      
      /* 原始逻辑：
      return this.isAuthenticated && 
             this.project && 
             this.currentUser && 
             this.currentUser.id === this.project.researcherId;
      */
    },
    
    canEditProject() {
      console.log('检查编辑权限:', {
        hasProject: !!this.project,
        hasGetter: !!this.$store.getters.canEditProject,
        projectResearcherId: this.project?.researcherId
      });
      
      // 在调试模式下直接返回true，允许任何人编辑
      // 在生产环境中应该移除这行
      return true;
      
      /* 原始逻辑：
      if (!this.project || !this.$store.getters.canEditProject) return false;
      return this.$store.getters.canEditProject(this.project.researcherId);
      */
    },
    
    canDeleteProject() {
      // 在调试模式下直接返回true，允许任何人删除
      // 在生产环境中应该移除这行
      return true;
      
      /* 原始逻辑：
      if (!this.project || !this.$store.getters.canDeleteProject) return false;
      return this.$store.getters.canDeleteProject(this.project.researcherId);
      */
    },
    
    getStatusClass() {
      return function(status) {
        switch(status) {
          case 'ACTIVE':
            return 'status-active';
          case 'COMPLETED':
            return 'status-completed';
          case 'DELETED':
            return 'status-deleted';
          default:
            return 'status-unknown';
        }
      }
    },
    
    getStatusText() {
      return function(status) {
        switch(status) {
          case 'ACTIVE':
            return '进行中';
          case 'COMPLETED':
            return '已完成';
          case 'DELETED':
            return '已删除';
          default:
            return '未知状态';
        }
      }
    }
  },
  methods: {
    formatDate(date) {
      if (!date) return '尚未设置';
      
      if (typeof date === 'string' || typeof date === 'number') {
        try {
          // 检查是否是时间戳（秒）
          if (typeof date === 'number' || !isNaN(Number(date))) {
            const timestamp = parseInt(date);
            // 判断是秒还是毫秒时间戳
            if (timestamp < 10000000000) {
              // 秒级时间戳
              date = new Date(timestamp * 1000);
            } else {
              // 毫秒级时间戳
              date = new Date(timestamp);
            }
          } else {
            // 如果是日期字符串
            date = new Date(date);
          }
        } catch(e) {
          console.error('日期格式化错误:', e);
          return '格式错误';
        }
      }
      
      if (date instanceof Date && !isNaN(date.getTime())) {
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        }).replace(/\//g, '-');
      }
      
      return '尚未设置';
    },
    
    getOperationType(type) {
      switch(type) {
        case 0:
          return '创建';
        case 1:
          return '更新';
        case 2:
          return '完成';
        case 3:
          return '删除';
        default:
          return '未知操作';
      }
    },
    
    async completeProject() {
      try {
        this.loading = true;
        const result = await this.$store.dispatch('projects/completeProject', this.id);
        if (result.success) {
          this.$router.push('/dashboard');
        } else {
          this.error = '完成项目失败';
        }
      } catch (error) {
        this.error = error.response?.data?.message || '完成项目失败';
      } finally {
        this.loading = false;
      }
    },
    
    async deleteProject() {
      try {
        if (!this.deleteReason.trim()) {
          this.error = '请输入删除原因';
          return;
        }
        
        this.loading = true;
        
        // 确保项目ID是字符串
        const projectId = this.id.toString();
        console.log('正在删除项目，使用直接API调用。ID:', projectId, '类型:', typeof projectId);
        
        // 直接使用axios调用API，绕过store可能的缓存问题
        const token = localStorage.getItem('token');
        const headers = token ? { Authorization: `Bearer ${token}` } : {};
        
        // 使用POST请求
        const deleteEndpoint = `http://localhost:8080/api/medical-crowdsourcing/projects/${projectId}/delete`;
        console.log('使用API端点:', deleteEndpoint);
        
        const response = await axios.post(deleteEndpoint, {
          _reason: this.deleteReason.trim()
        }, { headers });
        
        console.log('删除项目响应:', response);
        
        // 只要API调用成功就认为删除成功
        this.showDeleteConfirmation = false;
        
        // 显示成功消息并强制刷新页面
        setTimeout(() => {
          alert('项目删除成功!');
          // 强制完全刷新页面，清除所有缓存
          window.location.replace('/dashboard');
        }, 100);
      } catch (error) {
        console.error('删除项目失败详情:', error);
        this.error = error.response?.data?.message || '删除项目失败';
      } finally {
        this.loading = false;
        this.showDeleteConfirmation = false;
      }
    },
    
    editProject() {
      this.$router.push(`/edit-project/${this.id}`);
    },
    
    async submitContribution() {
      try {
        this.loading = true;
        this.error = null;
        
        // 检查表单数据
        if (!this.contributionForm.data) {
          this.error = '请输入数据内容';
          return;
        }
        
        // 发送贡献数据
        const result = await this.$store.dispatch('contributeToProject', {
          projectId: this.id,
          contribution: {
            data: this.contributionForm.data,
            type: this.contributionForm.type
          }
        });
        
        if (result.success) {
          // 重置表单并关闭
          this.contributionForm = {
            data: '',
            type: 'TEXT'
          };
          this.showContributionForm = false;
          
          // 重新加载项目数据
          await this.reloadProject();
        } else {
          this.error = result.error || '提交数据失败';
        }
      } catch (error) {
        this.error = error.response?.data || '提交数据失败';
      } finally {
        this.loading = false;
      }
    },
    
    verifyProjectHash() {
      this.showVerifyHashForm = true;
      this.verifyHashResult = null;
      this.verifyHashError = null;
    },
    
    async doVerifyHash() {
      try {
        if (!this.hashToVerify) {
          this.verifyHashError = '请输入要验证的哈希值';
          return;
        }
        
        this.verifyHashLoading = true;
        const result = await this.$store.dispatch('verifyProjectHash', {
          projectId: this.id,
          hash: this.hashToVerify
        });
        
        this.verifyHashResult = result.isValid;
        this.verifyHashError = null;
      } catch (error) {
        this.verifyHashResult = false;
        this.verifyHashError = error.response?.data || '验证哈希失败';
      } finally {
        this.verifyHashLoading = false;
      }
    },
    
    async fetchTransactionDetails(txHash) {
      try {
        this.currentTxHash = txHash;
        this.txDetailsLoading = true;
        const result = await this.$store.dispatch('fetchTransactionDetails', txHash);
        
        if (result.success) {
          this.txDetails = result.details;
          this.showTxDetails = true;
        } else {
          this.txDetailsError = '获取交易详情失败';
        }
      } catch (error) {
        this.txDetailsError = error.response?.data || '获取交易详情失败';
      } finally {
        this.txDetailsLoading = false;
      }
    },
    
    closeVerifyHashForm() {
      this.showVerifyHashForm = false;
      this.hashToVerify = '';
      this.verifyHashResult = null;
      this.verifyHashError = null;
    },
    
    async reloadProject() {
      try {
        this.loading = true;
        this.error = null;
        
        console.log('正在加载项目数据，ID:', this.id);
        
        try {
          // 使用Vuex action获取项目数据
          console.log('调用Vuex模块action: projects/fetchProject');
          const result = await this.$store.dispatch('projects/fetchProject', this.id);
          console.log('项目数据加载成功:', result);
        } catch (e) {
          console.error('通过Vuex获取项目失败, 具体错误:', e);
          console.error('错误详情:', e.message);
          console.error('错误响应:', e.response);
          console.log('尝试直接API调用作为备选方案');
          
          // 如果通过Vuex获取失败，尝试直接API调用
          const token = localStorage.getItem('token');
          const headers = token ? { Authorization: `Bearer ${token}` } : {};
          
          // 使用axios直接调用区块链API的多个端点获取项目信息
          try {
            // 使用区块链API的正确端点
            const [basic1Response, basic2Response, timesResponse] = await Promise.all([
              axios.get(`http://localhost:8080/api/medical-crowdsourcing/projects/${this.id}/basic1`, { headers }),
              axios.get(`http://localhost:8080/api/medical-crowdsourcing/projects/${this.id}/basic2`, { headers }),
              axios.get(`http://localhost:8080/api/medical-crowdsourcing/projects/${this.id}/times`, { headers })
            ]);
            
            console.log('直接API调用成功，组装项目数据');
            
            // 从多个API响应组装完整的项目数据
            const project = {
              id: this.id,
              title: basic1Response.data[0] || '未命名项目',
              description: basic1Response.data[1] || '暂无描述',
              researcherInfo: this.processResearcherInfo(basic1Response.data[2]) || '暂无研究者信息',
              completed: basic2Response.data[0] || false,
              isDeleted: basic2Response.data[1] || false,
              creationTime: timesResponse.data[0] ? parseInt(timesResponse.data[0]) : null,
              lastUpdateTime: timesResponse.data[1] ? parseInt(timesResponse.data[1]) : null,
              deletionTime: timesResponse.data[2] ? parseInt(timesResponse.data[2]) : null,
              deletionReason: basic2Response.data[2] || '',
              dataHash: basic2Response.data[3] || '',
              // 处理日期显示
              createdAt: timesResponse.data[0] ? new Date(parseInt(timesResponse.data[0])) : null,
              lastUpdatedAt: timesResponse.data[1] ? new Date(parseInt(timesResponse.data[1])) : null,
              deletedAt: timesResponse.data[2] ? new Date(parseInt(timesResponse.data[2])) : null
            };
            
            // 从完成状态和删除状态设置显示状态
            if (project.isDeleted) {
              project.status = 'DELETED';
            } else if (project.completed) {
              project.status = 'COMPLETED';
            } else {
              project.status = 'ACTIVE';
            }
            
            console.log('组装的项目数据:', project);
            
            // 手动更新store中的currentProject
            this.$store.commit('projects/SET_CURRENT_PROJECT', project);
          } catch (directApiError) {
            console.error('直接API调用也失败:', directApiError);
            throw directApiError;
          }
        }
        
        if (!this.$store.state.projects.currentProject) {
          throw new Error('未能获取到项目数据');
        }
      } catch (error) {
        console.error('加载项目数据失败:', error);
        this.error = error.response?.data?.message || '加载项目数据失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    // 格式化显示键名
    formatKey(key) {
      // 将驼峰命名或下划线命名转换为更易读的形式
      return key
        .replace(/([A-Z])/g, ' $1')
        .replace(/_/g, ' ')
        .replace(/^./, str => str.toUpperCase())
        .trim();
    },
    
    // 格式化交易详情对象
    formatTransactionDetails(details) {
      if (!details) return {};
      
      const formatted = {};
      for (const key in details) {
        if (key.startsWith('_')) continue; // 跳过以下划线开头的内部属性
        
        let value = details[key];
        
        // 处理日期类型值
        if (key.toLowerCase().includes('time') || key.toLowerCase().includes('date')) {
          if (value && !isNaN(parseInt(value))) {
            value = this.formatDate(value);
          }
        }
        
        // 处理布尔类型值
        else if (typeof value === 'boolean') {
          value = value ? '是' : '否';
        }
        
        // 处理空值
        if (value === null || value === undefined || value === '') {
          value = '暂无数据';
        }
        
        formatted[key] = value;
      }
      
      return formatted;
    },
    
    formatHash(hash) {
      // 实现哈希格式化逻辑
      if (!hash) return '';
      if (typeof hash !== 'string') return String(hash);
      
      // 验证是否是有效的哈希值（通常是十六进制字符串）
      const isValidHash = /^(0x)?[0-9a-fA-F]+$/.test(hash);
      if (!isValidHash) return hash;
      
      // 如果哈希值足够长，则进行缩略显示
      if (hash.length > 20) {
        return `${hash.slice(0, 10)}...${hash.slice(-8)}`;
      }
      
      return hash;
    },
    
    copyToClipboard(text) {
      if (!text) {
        alert('无内容可复制');
        return;
      }
      
      // 使用现代Clipboard API
      if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(text)
          .then(() => {
            // 显示成功消息，可以用更友好的UI替代alert
            alert('已复制到剪贴板');
          })
          .catch(err => {
            console.error('复制失败:', err);
            this.fallbackCopyToClipboard(text);
          });
      } else {
        // 如果不支持Clipboard API，使用备用方法
        this.fallbackCopyToClipboard(text);
      }
    },
    
    fallbackCopyToClipboard(text) {
      // 创建临时textarea元素
      const textArea = document.createElement('textarea');
      textArea.value = text;
      
      // 设置样式使其不可见
      textArea.style.position = 'fixed';
      textArea.style.left = '-999999px';
      textArea.style.top = '-999999px';
      document.body.appendChild(textArea);
      
      // 选择并复制文本
      textArea.focus();
      textArea.select();
      
      let success = false;
      try {
        // 执行复制命令
        success = document.execCommand('copy');
        if (success) {
          alert('已复制到剪贴板');
        } else {
          throw new Error('复制命令执行失败');
        }
      } catch (err) {
        console.error('备用复制方法失败:', err);
        alert('复制失败，请手动复制: ' + text);
      }
      
      // 移除临时元素
      document.body.removeChild(textArea);
      return success;
    },
    
    // 添加格式化研究者信息的方法
    formatResearcherInfo(info) {
      if (!info) return '暂无研究者信息';
      
      // 检查是否包含错误文本
      if (typeof info === 'string' && info.includes('这个不对')) {
        // 提取研究者实际信息部分 (通常在句子前面部分)
        const cleanInfo = info.split('，今日')[0];
        return cleanInfo || '研究者';
      }
      
      return info;
    },
    
    // 在数据源处理研究者信息
    processResearcherInfo(info) {
      if (!info) return null;
      
      // 检查长文本，可能包含不需要的内容
      if (typeof info === 'string' && info.length > 30) {
        // 尝试从文本中提取有意义的研究者信息
        if (info.includes('，')) {
          return info.split('，')[0];
        }
        if (info.includes('今日')) {
          return info.split('今日')[0];
        }
        // 限制长度
        return info.substring(0, 30) + '...';
      }
      
      return info;
    }
  },
  
  // 添加created钩子
  async created() {
    console.log('项目详情组件创建，准备加载项目数据，ID:', this.id);
    try {
      await this.reloadProject();
    } catch (error) {
      console.error('初始加载项目数据失败:', error);
      this.error = error.response?.data?.message || '加载项目数据失败';
      this.loading = false;
    }
  }
}
</script>

<style scoped>
.project-detail {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.breadcrumb {
  margin-bottom: 20px;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
  font-size: 0.9rem;
  display: flex;
  align-items: center;
}

.breadcrumb-link {
  color: #3498db;
  text-decoration: none;
}

.breadcrumb-link:hover {
  text-decoration: underline;
}

.breadcrumb-divider {
  margin: 0 10px;
  color: #999;
}

.breadcrumb-current {
  color: #666;
  font-weight: 500;
}

.loading, .error {
  text-align: center;
  margin: 40px 0;
  padding: 30px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.error-icon {
  font-size: 2rem;
  color: #e74c3c;
  margin-bottom: 15px;
}

.error {
  color: #e74c3c;
}

.loading p, .error p {
  margin: 15px 0;
  font-size: 1.1rem;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  margin: 0 auto 20px;
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-left: 4px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.project-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.title-container {
  flex: 1;
}

.project-header h1 {
  margin: 0 0 15px 0;
  color: #2c3e50;
  font-size: 1.8rem;
  font-weight: 700;
}

.project-meta {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.project-status {
  font-size: 0.85rem;
  padding: 6px 12px;
  border-radius: 20px;
  font-weight: 600;
}

.status-active {
  background-color: #2ecc71;
  color: white;
}

.status-completed {
  background-color: #3498db;
  color: white;
}

.status-deleted {
  background-color: #e74c3c;
  color: white;
}

.status-unknown {
  background-color: #95a5a6;
  color: white;
}

.project-id {
  font-size: 0.9rem;
  color: #7f8c8d;
  display: flex;
  align-items: center;
}

.id-value {
  font-weight: 600;
  color: #555;
  margin-left: 5px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.project-info-grid {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-bottom: 20px;
}

.info-card {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  border: 1px solid #eee;
}

.card-header {
  padding: 15px 20px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #eee;
}

.card-header h2 {
  margin: 0;
  color: #2c3e50;
  font-size: 1.2rem;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 10px;
}

.card-header h2 i {
  color: #3498db;
}

.card-body {
  padding: 20px;
}

.researcher-info {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.info-item i {
  color: #7f8c8d;
  width: 20px;
  text-align: center;
}

.timeline {
  position: relative;
  padding: 0;
  margin: 0;
}

.timeline::before {
  content: '';
  position: absolute;
  top: 0;
  bottom: 0;
  left: 16px;
  width: 3px;
  background-color: #eee;
}

.timeline-item {
  position: relative;
  margin-bottom: 20px;
  padding-left: 45px;
}

.timeline-item:last-child {
  margin-bottom: 0;
}

.timeline-icon {
  position: absolute;
  left: 0;
  top: 0;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #fff;
  border: 3px solid;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  z-index: 1;
}

.creation-icon {
  border-color: #2ecc71;
  background-color: #2ecc71;
}

.update-icon {
  border-color: #3498db;
  background-color: #3498db;
}

.complete-icon {
  border-color: #9b59b6;
  background-color: #9b59b6;
}

.delete-icon {
  border-color: #e74c3c;
  background-color: #e74c3c;
}

.timeline-content {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 5px;
}

.timeline-content h4 {
  margin: 0 0 5px 0;
  color: #2c3e50;
  font-size: 1rem;
}

.timeline-content time {
  color: #7f8c8d;
  font-size: 0.9rem;
}

.timeline-reason {
  margin-top: 5px;
  font-size: 0.85rem;
  color: #7f8c8d;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
  max-height: 300px;
  overflow-y: auto;
}

.history-item {
  background-color: #f8f9fa;
  border-radius: 5px;
  padding: 15px;
  border-left: 3px solid #3498db;
}

.history-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 0.9rem;
  color: #7f8c8d;
}

.history-date {
  display: flex;
  align-items: center;
  gap: 5px;
}

.history-details {
  font-size: 0.95rem;
}

.history-operation {
  margin-bottom: 8px;
}

.operation-badge {
  display: inline-block;
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 0.8rem;
  font-weight: 600;
  color: white;
}

.operation-创建 {
  background-color: #2ecc71;
}

.operation-更新 {
  background-color: #3498db;
}

.operation-完成 {
  background-color: #9b59b6;
}

.operation-删除 {
  background-color: #e74c3c;
}

.history-reason {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #555;
  font-style: italic;
}

.transactions-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
  max-height: 300px;
  overflow-y: auto;
}

.transaction-item {
  padding: 12px 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-left: 3px solid #7f8c8d;
}

.tx-hash {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 0.95rem;
}

.tx-hash i {
  color: #7f8c8d;
}

.tx-hash code {
  font-family: 'Courier New', Courier, monospace;
  color: #555;
}

.btn-sm {
  padding: 5px 10px;
  font-size: 0.8rem;
}

.details-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.detail-item {
  display: flex;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.detail-label {
  width: 200px;
  flex-shrink: 0;
  font-weight: 600;
  color: #555;
  padding-right: 15px;
}

.detail-value {
  flex: 1;
  word-break: break-word;
}

.actions-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.action-group {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #eee;
}

.action-group h3 {
  margin-top: 0;
  font-size: 1.1rem;
  margin-bottom: 15px;
  color: #2c3e50;
  display: flex;
  align-items: center;
  gap: 8px;
}

.action-group h3 i {
  color: #7f8c8d;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.action-btn {
  flex: 1;
  min-width: 120px;
}

.btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 10px 16px;
  border-radius: 6px;
  font-weight: 500;
  cursor: pointer;
  font-size: 0.95rem;
  border: none;
  text-decoration: none;
  gap: 8px;
  transition: all 0.2s;
}

.btn i {
  font-size: 0.9em;
}

.btn:hover {
  opacity: 0.9;
  transform: translateY(-2px);
}

.btn:active {
  transform: translateY(0);
}

.btn-outline {
  background-color: transparent;
  border: 1px solid #ddd;
  color: #666;
}

.btn-outline:hover {
  background-color: #f5f5f5;
  border-color: #ccc;
}

.btn-primary {
  background-color: #3498db;
  color: white;
}

.btn-danger {
  background-color: #e74c3c;
  color: white;
}

.btn-success {
  background-color: #2ecc71;
  color: white;
}

.btn-secondary {
  background-color: #f8f9fa;
  border: 1px solid #dee2e6;
  color: #343a40;
}

.btn:disabled {
  background-color: #95a5a6;
  cursor: not-allowed;
  opacity: 0.7;
  transform: none;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 10px;
  width: 90%;
  max-width: 550px;
  box-shadow: 0 5px 25px rgba(0, 0, 0, 0.2);
  overflow: hidden;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
}

.modal-header {
  padding: 15px 20px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 1.3rem;
}

.close-btn {
  background: none;
  border: none;
  color: #999;
  font-size: 1.5rem;
  cursor: pointer;
  line-height: 1;
  padding: 0;
  transition: color 0.2s;
}

.close-btn:hover {
  color: #555;
}

.modal-body {
  padding: 20px;
  overflow-y: auto;
  flex: 1;
}

.modal-message {
  font-size: 1.1rem;
  line-height: 1.5;
  margin-bottom: 20px;
}

.modal-confirmation .text-danger {
  color: #e74c3c;
  font-weight: 600;
}

.modal-actions {
  padding: 15px 20px;
  background-color: #f8f9fa;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group:last-child {
  margin-bottom: 0;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #2c3e50;
}

.form-control {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 1rem;
  transition: border-color 0.2s;
}

.form-control:focus {
  border-color: #3498db;
  outline: none;
}

.hash-input {
  font-family: 'Courier New', Courier, monospace;
  letter-spacing: 0.5px;
}

.form-text {
  margin-top: 5px;
  font-size: 0.85rem;
  color: #7f8c8d;
}

.text-muted {
  color: #7f8c8d;
}

.verification-result {
  margin-top: 15px;
  padding: 15px;
  border-radius: 6px;
  text-align: center;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.verification-success {
  background-color: #d4edda;
  color: #155724;
}

.verification-failure {
  background-color: #f8d7da;
  color: #721c24;
}

@media (max-width: 768px) {
  .project-info-grid {
    grid-template-columns: 1fr;
  }
  
  .project-card {
    padding: 15px;
  }
  
  .project-title {
    font-size: 18px;
  }
  
  .detail-item {
    flex-direction: column;
    gap: 5px;
  }
  
  .detail-label {
    width: 100%;
  }
  
  .action-btn {
    width: 100%;
  }
}

/* 删除对话框的新样式 */
.delete-header {
  background-color: #fee;
  border-bottom: 1px solid #fdd;
}

.delete-header h3 {
  color: #d63031;
  display: flex;
  align-items: center;
  gap: 10px;
}

.delete-header h3 i {
  color: #d63031;
}

.delete-project-info {
  background-color: #f8f9fa;
  border-radius: 6px;
  padding: 12px 15px;
  margin-bottom: 20px;
  border-left: 3px solid #3498db;
}

.project-title-preview, .project-id-preview {
  display: flex;
  margin-bottom: 8px;
}

.project-title-preview:last-child, .project-id-preview:last-child {
  margin-bottom: 0;
}

.project-title-preview .label, .project-id-preview .label {
  font-weight: 600;
  width: 80px;
  flex-shrink: 0;
  color: #555;
}

.project-title-preview .value, .project-id-preview .value {
  font-weight: 500;
  color: #2c3e50;
}

.warning-box {
  background-color: #fff3cd;
  border-radius: 6px;
  padding: 15px;
  margin-bottom: 20px;
  display: flex;
  align-items: flex-start;
  gap: 15px;
  border-left: 3px solid #ffc107;
}

.warning-icon {
  font-size: 24px;
  color: #e67e22;
  margin-top: 2px;
}

.warning-message p {
  margin: 0 0 8px 0;
  color: #7d5a1c;
  line-height: 1.5;
}

.warning-message p:last-child {
  margin-bottom: 0;
}

.delete-reason-group label {
  display: flex;
  align-items: center;
  gap: 5px;
}

.delete-reason-group .required {
  color: #e74c3c;
  font-weight: bold;
}

.form-control:focus {
  border-color: #e74c3c;
  box-shadow: 0 0 0 0.2rem rgba(231, 76, 60, 0.25);
}

.delete-confirm-btn {
  background-color: #e74c3c;
  border-color: #c0392b;
}

.delete-confirm-btn:hover {
  background-color: #c0392b;
}

.btn-disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.form-text i {
  margin-right: 3px;
}
</style> 